package net.socket;

import java.io.File;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class JHTTP extends Thread
{
	private File documentRootDirectory;
	private String indexFileName ="index.html";
	private ServerSocket server;
	private int numThreads = 50;
	public JHTTP(File documentRootDirectory,int port,String indexFileName) throws IOException
	{
		if(!documentRootDirectory.isDirectory())
		{
			throw new IOException("not exist");
		}
		this.documentRootDirectory = documentRootDirectory;
		this.indexFileName = indexFileName;
		this.server = new ServerSocket(port);
	}
	public JHTTP(File documentDirectory,int port) throws IOException
	{
		this(documentDirectory, port, "index.html");
	}
	public JHTTP(File documentRootDirectory) throws IOException
	{
		this(documentRootDirectory, 80);
	}
	@Override
	public void run()
	{
		for (int i = 0; i < numThreads; i++)
		{
			try
			{
				Thread t = new Thread(new RequestProcessor(documentRootDirectory, indexFileName));
				t.start();
			}
			catch (IllegalAccessException e)
			{
				e.printStackTrace();
			}
		}
		while(true)
		{
			try
			{
				Socket request = server.accept();
				RequestProcessor.processRequest(request);
			}
			catch (Exception e)
			{
			}
		}
	}
	public static void main(String[] args)
	{
		File docroot;
		try
		{
			docroot = new File(args[0]);
		}
		catch (Exception e)
		{
			return;
		}
		int port;
		try
		{
			port = Integer.parseInt(args[1]);
			if(port<0||port>65535)
			{
				port = 80;
			}
		}
		catch (Exception e)
		{
			port = 80;
		}
		try
		{
			JHTTP webserver = new JHTTP(docroot);
			webserver.start();
		}
		catch (Exception e)
		{
		}
	}
}
